<template>
  <a-modal
    style="top: 1px;"
    :title="title"
    :width="width"
    v-model:open="visible"
    :keyboard="false"
    :maskClosable="false"
  >
        <a-form ref="formRef" :model="formState" :rules="formRules">
          <a-row>
            <a-col :offset="6">
              <a-form-item name="file">
                <a-upload
                  v-show="title === '新增'"
                  name="file"
                  :multiple="false"
                  :showUploadList="true"
                  :fileList="fileList"
                  :beforeUpload="beforeUpload">
                  <a-button>
                    <UploadOutlined style="margin-right: 8px"/>
                    选择文件
                  </a-button>
                </a-upload>
              </a-form-item>
            </a-col>
          </a-row>
          <!-- 修正 :getter 为 :gutter -->
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-item name="memo" label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol">
                <a-textarea v-model:value="formState.memo" :autoSize="{ minRows: 3, maxRows: 6 }" showCount :maxlength="150" />
              </a-form-item>
            </a-col>
          </a-row>
          <!-- 修正 :getter 为 :gutter -->
          <a-row :gutter="24" v-show="title === '参数配置'">
            <a-col :span="24">
              <a-form-item name="config" label="参数(JSON格式;非必填)" :labelCol="labelCol2" :wrapperCol="wrapperCol">
                <a-textarea v-model:value="formState.config" :autoSize="{ minRows: 3, maxRows: 6 }" showCount :maxlength="150" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <template #footer>
          <a-button
            type="primary"
            :disabled="fileList.length === 0 && title === '新增'"
            :loading="uploading"
            style="margin-top: 16px"
            @click="save"
          >
            {{ uploading ? 'Uploading' : '保存' }}
          </a-button>
        </template>
    </a-modal>
</template>
<script setup>
import { ref, reactive, nextTick } from 'vue';
import { postAction } from '@/utils/request.js';
import { pick } from "lodash";
import { message } from 'ant-design-vue';

// 定义 props
const props = defineProps(['url', 'fileList']);
// 定义 emits
const emit = defineEmits(['sync']);
// 定义表单引用
const formRef = ref(null);

// 集中定义表单验证规则
const formRules = reactive({
  file: [
    {
      validator: (rule, value) => {
        if (title.value === '新增' && props.fileList.length === 0) {
          return Promise.reject('请选择上传文件');
        } else {
          return Promise.resolve();
        }
      },
      trigger: 'change'
    }
  ],
  memo: [],
  config: [
    {
      validator: (rule, value) => {
        try {
          // 空或有效json字符，则通过
          if (value) {
            JSON.stringify(JSON.parse(value));
          }
          return Promise.resolve();
        } catch (e) {
          console.error(e);
          return Promise.reject('请输入正常json格式');
        }
      },
      trigger: 'blur'
    }
  ]
});

// 定义响应式数据
const title = ref('新增');
const width = ref('45%');
const visible = ref(false);
const dateFormat = ref('YYYY-MM-DD');
const formState = reactive({
  memo: '',
  config: ''
});
const uploading = ref(false);
const labelCol = ref({
  xs: { span: 24 },
  sm: { span: 10 }
});
const wrapperCol = ref({
  xs: { span: 24 },
  sm: { span: 14 }
});
const labelCol2 = ref({
  xs: { span: 20 },
  sm: { span: 6 }
});
const settings = ref({});

//// simple vars

// 定义方法
const init = () => {
  uploading.value = false;
  nextTick(() => {
    formRef.value?.resetFields(); //会清验证；其实也会清值
  })
};

const add = (record) => { //有部分是固定信息
  title.value = '新增';
 // console.error( JSON.stringify(record));
  edit(record);
};

const edit = (record, titleText = '') => {
  init();
  if (record && record.filePath) {
    title.value = titleText? `${titleText}-${record.fileName}` : '编辑';
    nextTick(() => {
      Object.assign(formState, pick(record, Object.keys(formState)))
    });
    Object.assign(settings.value, pick(record, ['filePath', 'bucketName']));
  }else{
    Object.assign(settings.value, record);
  }
  visible.value = true;
};

const close = () => {
  visible.value = false;
};

const beforeUpload = (file) => {
  if (file.size > 80 * 1024 * 1024) {
    message.error('上传文件不能大于80M！');
    return false;
  }
  props.fileList.length = 0;
  props.fileList.push(file);
  return false;
};

const save = () => {
  formRef.value
      .validate()
      .then(() => {
        const {memo, config} = formState;
        let {bucketName, filePath} = settings;
        let filename = filePath && filePath.split('/').pop();
        const formData = new FormData();
        props.fileList.forEach((file) => {
            //console.error("file:",file);
            formData.append('file', file);
            filename = file.name;
        });

        for (const key in settings.value) {
          formData.append(key, settings.value[key]);
        }
        formData.append('config', config || '');
        formData.append('memo', memo || '');
        formData.append('filename', filename);
        uploading.value = true;
        postAction(props.url.oss, formData).then((res) => {
          if (res.success) {
            emit('sync');
            close();
            message.success('保存成功!');
          } else {
            let errMsg = res.message;
            if (errMsg.includes('maximum allowed metadata size')) {
              errMsg = '备注超过最大允许字数';
            }
            message.error(`${errMsg} ,保存失败！`);
          }
          props.fileList.pop();
          uploading.value = false;
        });
      })
      .catch(error => {
        message.warning("表单信息验证失败");
        console.log('error', error);
      });
}

defineExpose({ add, edit})
</script>

